//
//  RBLoginController.m
//  MaterialXBUser
//
//  Created by XBWH on 2024/3/6.
//

#import "RBLoginController.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "RBVerifyCodeController.h"
#import "RBGenerateUserSigIn.h"
#import "RBBindPhoneController.h"

@interface RBLoginController ()<ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding,UITextFieldDelegate>
@property(strong,nonatomic)UIButton *rbCloseButton;
@property(strong,nonatomic)UILabel *rbNameLabel;
@property(strong,nonatomic)UIView *rbPhoneView;
@property(strong,nonatomic)UITextField *rbPhoneTf;
@property(strong,nonatomic)UIView *rbPhoneLineView;
@property(strong,nonatomic)UIButton *rbCodeButton;
@property(strong,nonatomic)UIButton *rbAgreeButton;
@property(strong,nonatomic)UILabel *rbServerLabel;
@property(strong,nonatomic)UILabel *rbInfoLabel;
@property(strong,nonatomic)UIButton *rbAppleButton;

@property(assign,nonatomic)BOOL isAgreeProtl;
@end

@implementation RBLoginController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self rb_initViewUI];
    [self rb_layoutView];
    self.isAgreeProtl = YES;
    
    NSString *titleStr =@"我已阅读并同意《用户服务协议》《隐私政策》";
    NSString *userStr = @"《用户服务协议》";
    NSString *privacyStr = @"《隐私政策》";
    NSMutableAttributedString *attributedString=[[NSMutableAttributedString alloc]initWithString:titleStr];
    [attributedString addAttribute:NSFontAttributeName value:RBPingFangFont(13) range:NSMakeRange(0, titleStr.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:RBColor(242, 48, 48) range:NSMakeRange(titleStr.length-userStr.length-privacyStr.length, userStr.length+privacyStr.length)];
    self.rbServerLabel.enabledTapEffect = NO;
    self.rbServerLabel.attributedText =attributedString;
    MJWeakSelf
    [self.rbServerLabel rb_addAttributeTapActionWithStrings:@[userStr,privacyStr] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
        NSURL *htmlFileURL;
        NSString *titleStr = @"";
        if ([string isEqualToString:userStr]) {
            htmlFileURL = [[NSBundle mainBundle] URLForResource:@"service" withExtension:@"html"];
            titleStr = @"用户协议";
        } else if ([string isEqualToString:privacyStr]){
            htmlFileURL = [[NSBundle mainBundle] URLForResource:@"privacy" withExtension:@"html"];
            titleStr = @"隐私政策";
        }
        RBWKWebViewController *webViewController = [[RBWKWebViewController alloc] initWithHTMLFilePath: htmlFileURL];
        webViewController.title = titleStr;
        [weakSelf.navigationController pushViewController:webViewController animated:YES];
    }];
}

-(void)rb_initViewUI{
    self.rbCloseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbCloseButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [self.rbCloseButton addTarget:self action:@selector(closeBtnTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rbCloseButton];
    self.rbNameLabel = [UILabel rb_labelWithTitle:@"登录/注册红料" color:RBColor(51, 51, 51) font:RBPingFangBlodFont(24) alignment:NSTextAlignmentLeft];
    [self.view addSubview:self.rbNameLabel];
    self.rbPhoneView = [[UIView alloc] init];
    self.rbPhoneView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.rbPhoneView];
    self.rbPhoneTf = [[UITextField alloc] init];
    self.rbPhoneTf.textColor = RBColor(51, 51, 51);
    NSMutableDictionary *iphoneDict = [@{NSForegroundColorAttributeName:RBColor(179, 179, 179), NSFontAttributeName:RBPingFangFont(14)} mutableCopy];
    NSMutableAttributedString *iphoneAttPlace = [[NSMutableAttributedString alloc] initWithString:@"请输入手机号" attributes:iphoneDict];
    self.rbPhoneTf.attributedPlaceholder = iphoneAttPlace;
    self.rbPhoneTf.secureTextEntry = NO;
    self.rbPhoneTf.delegate = self;
    self.rbPhoneTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.rbPhoneTf.keyboardType = UIKeyboardTypePhonePad;
    [self.rbPhoneTf addTarget:self action:@selector(textFiledChanged:) forControlEvents:UIControlEventEditingChanged];
    self.rbPhoneTf.font = RBPingFangFont(16);
    [self.rbPhoneView addSubview:self.rbPhoneTf];
    self.rbPhoneLineView = [[UIView alloc] init];
    self.rbPhoneLineView.backgroundColor = RBColor(237, 237, 237);
    [self.rbPhoneView addSubview:self.rbPhoneLineView];
    self.rbCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.rbCodeButton addTarget:self action:@selector(codeButtonTap) forControlEvents:UIControlEventTouchUpInside];
    self.rbCodeButton.titleLabel.font = RBPingFangFont(16);
    [self.rbCodeButton setTitleColor:RBColor(255, 255, 255) forState:UIControlStateNormal];
    self.rbCodeButton.backgroundColor = RBColor(217, 217, 217);
    [self.view addSubview:self.rbCodeButton];
    self.rbAgreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbAgreeButton setImage:[UIImage imageNamed:@"uncheck"] forState:UIControlStateNormal];
    [self.rbAgreeButton setImage:[UIImage imageNamed:@"check"] forState:UIControlStateSelected];
    [self.rbAgreeButton addTarget:self action:@selector(agreeButtonTap) forControlEvents:UIControlEventTouchUpInside];
    self.rbAgreeButton.selected = YES;
    [self.view addSubview:self.rbAgreeButton];
    self.rbServerLabel = [UILabel rb_labelWithTitle:@"我已阅读并同意《用户服务协议》《隐私政策》" color:RBColor(153, 153, 153) font:RBPingFangFont(13) alignment:NSTextAlignmentLeft];
    [self.view addSubview:self.rbServerLabel];
    self.rbInfoLabel = [UILabel rb_labelWithTitle:@"------  其他方式登录  ------" color:RBColor(153, 153, 153) font:RBPingFangFont(13) alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.rbInfoLabel];
    self.rbAppleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbAppleButton setImage:[UIImage imageNamed:@"appleLogin"] forState:UIControlStateNormal];
    [self.rbAppleButton setImage:[UIImage imageNamed:@"appleLogin"] forState:UIControlStateHighlighted];
    [self.rbAppleButton addTarget:self action:@selector(appleLoginTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rbAppleButton];
}
-(void)rb_layoutView{
    [self.rbCloseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(RBScaleWidth(10));
        make.top.mas_equalTo(RBSTATUS_BAR_HEIGHT+RBScaleWidth(10));
        make.width.height.mas_equalTo(RBScaleWidth(20));
    }];
    [self.rbNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbCloseButton.mas_bottom).mas_offset(RBScaleWidth(25));
        make.left.mas_equalTo(RBScaleWidth(20));
    }];
    [self.rbPhoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbNameLabel.mas_bottom).mas_offset(RBScaleWidth(50));
        make.left.mas_equalTo(RBScaleWidth(20));
        make.right.mas_equalTo(-RBScaleWidth(20));
        make.height.mas_equalTo(RBScaleWidth(60));
    }];
    [self.rbPhoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    [self.rbPhoneTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.rbPhoneLineView.mas_top);
    }];
    [self.rbCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbPhoneView.mas_bottom).mas_offset(RBScaleWidth(30));
        make.width.mas_equalTo(RBScaleWidth(335));
        make.height.mas_equalTo(RBScaleWidth(48));
        make.centerX.mas_equalTo(0);
    }];
    self.rbCodeButton.layer.cornerRadius = RBScaleWidth(24);
    [self.rbServerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbCodeButton.mas_bottom).mas_equalTo(RBScaleWidth(30));
        make.centerX.mas_equalTo(0);
    }];
    [self.rbAgreeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.rbServerLabel.mas_centerY);
        make.right.mas_equalTo(self.rbServerLabel.mas_left).mas_offset(-RBScaleWidth(5));
        make.height.width.mas_equalTo(16);
    }];
    [self.rbInfoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(self.rbServerLabel.mas_bottom).mas_offset(RBScaleWidth(90));
        make.width.mas_equalTo(RBScaleWidth(260));
        make.height.mas_equalTo(RBScaleWidth(13));
    }];
    [self.rbAppleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_offset(RBScaleWidth(48));
        make.top.mas_equalTo(self.rbInfoLabel.mas_bottom).mas_offset(RBScaleWidth(19));
        make.centerX.mas_equalTo(0);
    }];
}
-(void)loadRBSmsURLData{
    NSString *phoneStr = [self.rbPhoneTf.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if ([RBTool rb_isEmptyStr:phoneStr]) {
        [MBProgressHUD rb_showAutoMessage:@"请输入正确的手机号" ToView:RBWindow];
        return;
    }
    if (!self.rbAgreeButton.selected) {
        [MBProgressHUD rb_showAutoMessage:@"请同意并接受用户协议和隐私" ToView:RBWindow];
        return;
    }
    
    MJWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"phone"] = phoneStr;
    dict[@"type"] = @"0";
    dict[@"term"] = @"user";
    [RBNetworkTool GET:RBSmsURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] intValue] == 1) {
            RBVerifyCodeController *verifyVc = [[RBVerifyCodeController alloc] init];
            verifyVc.loginType = weakSelf.loginType;
            verifyVc.source = weakSelf.source;
            verifyVc.selectedIndex = weakSelf.selectedIndex;
            verifyVc.phoneStr = phoneStr;
            [self.navigationController pushViewController:verifyVc animated:YES];
        }
    } error:^(id responseObject) {
        weakSelf.rbCodeButton.userInteractionEnabled = YES;
        [weakSelf.rbCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    } failure:^(NSError *error) {
        weakSelf.rbCodeButton.userInteractionEnabled = YES;
        [weakSelf.rbCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    }];
}
- (void)loadAppleLoginDataWithUserId:(NSString *)userId WithName:(NSString *)name WithEmail:(NSString *)email WithCode:(NSString *)code WithToken:(NSString *)token{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"userId"] = userId;
    dict[@"fullName"] = name;
    dict[@"email"] = email;
    dict[@"authorizationCode"] = code;
    dict[@"identityToken"] = token;
    MJWeakSelf
    [RBNetworkTool POST:RBAppleLoginURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
                        
            // 判断是否已经绑定
            NSString *iphoneStr = responseObject[@"result"][@"userInfo"][@"phone"];
            NSString *oauthIdStr = responseObject[@"result"][@"userInfo"][@"oauthId"];
            BOOL bindPhone = responseObject[@"result"][@"userInfo"][@"is_bind_phone"];
            if (bindPhone) {
                NSString *token = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"token"]];
                RBUserModel *userModel = [RBUserModel mj_objectWithKeyValues:responseObject[@"result"][@"userInfo"]];
                userModel.token = token;
                if (userModel.imSecret.length==0) {
                    userModel.imSecret = secretkey;
                }
                if (userModel.imAppId.length==0) {
                    userModel.imAppId = [NSString stringWithFormat:@"%d",sdkappid];
                }
                
                //保存用户信息
                [RBArchiveTool rb_saveUserModel:userModel];
                
                [[RBLogInAndOutTool shareInstance] rb_saveLogin:userModel.userId withAppId:SDKAPPID withUserSig:[RBGenerateUserSigIn genTestUserSig:userModel.userId]];
                
                // 通知更新个人信息
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RBUpDateUserInfmation" object:nil];
                // 登录成功通知刷新数据
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RBUpDateRefershData" object:nil];
            
                NSString *selectIndex = [NSString stringWithFormat:@"%ld",self.selectedIndex];
                NSDictionary *dict = @{
                                        @"logSelect":selectIndex,
                                        @"source":self.source?self.source:@""
                                       };
                [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"RBLoginSuccess" object:nil userInfo:dict]];
                
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
            }else{
                if (iphoneStr.length==0&&oauthIdStr.length>0) {
                    RBBindPhoneController *bingPhoneVc = [[RBBindPhoneController alloc] init];
                    bingPhoneVc.oauthId = oauthIdStr;
                    [self.navigationController pushViewController:bingPhoneVc animated:YES];
                }else{
                    [MBProgressHUD rb_showAutoMessage:@"登录失败，请重新登录" ToView:RBWindow];
                }
            }
        }
    } error:^(id responseObject) {
    } failure:^(NSError *error) {
    }];
}

-(void)textFiledChanged:(UITextField *)textField{
    if ([textField.text isEqualToString:@""]) {
        [self rb_UpdaterbCodeButtonState:nil];
    }
}
//手机号按位分割/分段显示
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSUInteger oldLength = textField.text.length;
    NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    //如果输入的不是数字,返回NO
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    // 如果是电话号码格式化，需要添加这三行代码
    NSMutableString *temString = [NSMutableString stringWithString:text];
    
    NSInteger spaceLength = 4;
    if (spaceLength == 4) {
        [temString insertString:@" " atIndex:0];
    }
    
    text = temString;
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, spaceLength)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == spaceLength) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, spaceLength)];
    }
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    //限制手机号位数
    NSString *tempPhoneNum = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSInteger maxValue = 11;
    if (tempPhoneNum.length >= maxValue + 1) {
        return NO;
    }
    //分段好赋值
    [textField setText:newString];
    
    //中间删除逻辑
    if (range.location < oldLength - 1 && oldLength != 0) {
        
        //如果删除的是一个空格,光标往前移动一位
        if ([string isEqualToString:@""]) {
            [self rb_cursorLocation:textField index:range.location];
        }else{
            //如果是在之前删除的位置增加一个数字,光标移动
            [self rb_cursorLocation:textField index:range.location + 1];
        }
    }
    //控制提交按钮是否可点击
    [self rb_UpdaterbCodeButtonState:[newString stringByReplacingOccurrencesOfString:@" " withString:@""]];
    
    return NO;
}
//让textField 移动到指定位置
- (void)rb_cursorLocation:(UITextField*)textField index:(NSInteger)index {
    NSRange range = NSMakeRange(index,0);
    UITextPosition *start = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location];
    UITextPosition *end = [textField positionFromPosition:start offset:range.length];
    [textField setSelectedTextRange:[textField textRangeFromPosition:start toPosition:end]];
}
-(void)rb_UpdaterbCodeButtonState:(NSString *)phoneStr{
    if (phoneStr.length<11) {
        self.rbCodeButton.enabled = NO;
        self.rbCodeButton.backgroundColor = RBColor(217, 217, 217);
    }else{
        self.rbCodeButton.enabled = YES;
        self.rbCodeButton.backgroundColor = RBColor(242, 48, 48);
    }
}
#pragma mark - ASAuthorizationControllerDelegate
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        NSString *state = credential.state;
        NSString * userID = credential.user;
        NSPersonNameComponents * fullName = credential.fullName;
        NSString *name = fullName.nickname;
        NSString * email = credential.email;
        NSString * authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
        
        NSString * identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        NSArray *authorizedScopes = credential.authorizedScopes;
        [self loadAppleLoginDataWithUserId:userID WithName:name WithEmail:email WithCode:authorizationCode WithToken:identityToken];
        
    }else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
        ASPasswordCredential * passwordCredential = (ASPasswordCredential *)authorization.credential;
        NSString * user = passwordCredential.user;
        NSString * password = passwordCredential.password;
        
    }
}
// 授权失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    [MBProgressHUD rb_showAutoMessage:errorMsg ToView:RBWindow];
}

#pragma mark- ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    return self.view.window;
}
#pragma mark - 响应事件
-(void)closeBtnTap{
    if (self.presentingViewController && self.navigationController.viewControllers.count == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)codeButtonTap{
    [self loadRBSmsURLData];
}
-(void)agreeButtonTap{
    if (!self.isAgreeProtl) {
        self.isAgreeProtl = YES;
        self.rbAgreeButton.selected = YES;
        [self.rbAgreeButton setImage:[UIImage imageNamed:@"check"] forState:UIControlStateSelected];
    } else {
        self.isAgreeProtl = NO;
        self.rbAgreeButton.selected = NO;
        [self.rbAgreeButton setImage:[UIImage imageNamed:@"uncheck"] forState:UIControlStateNormal];
    }
}
-(void)appleLoginTap{
    if (!self.rbAgreeButton.selected) {
        [MBProgressHUD rb_showAutoMessage:@"请同意并接受用户协议和隐私" ToView:RBWindow];
        return;
    }
    
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *appleIDProvider = [ASAuthorizationAppleIDProvider new];
        ASAuthorizationAppleIDRequest *request = appleIDProvider.createRequest;
        request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        controller.delegate = self;
        controller.presentationContextProvider = self;
        [controller performRequests];
    }else{
        [MBProgressHUD rb_showAutoMessage:@"该系统版本不可用Apple登录" ToView:RBWindow];
    }
}

@end
